import { clearJson } from '@utils'

import { listApi } from '@/api/conversation'

export const useConversationStore = defineStore('conversation', {
  state: () => ({
    active: null,
    list: [],
  }),
  getters: {
    hasUnread: ({ list }) => {
      return list?.some(item => item.unread > 0) ?? false
    }
  },
  actions: {
    /**
     * 获取会话列表
     * @param {*} params
     * @returns
     */
    async getList() {
      try {
        const r = await listApi()
        if (r && r.code === 0) {
          // 确保每个会话对象都有必要的字段
          const conversations = (r.data || []).map(conversation => {
            // 如果是群聊，确保group对象包含所有必要的字段
            if (conversation.group) {
              return {
                ...conversation,
                unread: 0,
                type: 'group',
                group: {
                  ...conversation.group,
                  id: conversation.group.id,
                  name: conversation.group.name,
                  avatar: conversation.group.avatar,
                  ownerId: conversation.group.ownerId,
                  memberCount: conversation.group.memberCount,
                  onlineCount: conversation.group.onlineCount
                }
              }
            }
            // 如果是私聊
            return {
              ...conversation,
              unread: 0,
              type: 'friend'
            }
          })
          this.list = conversations
        }
      } catch (error) {
        console.error('获取会话列表失败:', error)
        this.list = []
      }
    },
    /**
     * 新增会话 存在则更新消息
     * @param {*} conversation 
     */
    addConversation(conversation) {
      const { roomId, message } = conversation
      const exist = this.list.find(item => item.roomId === roomId) 
      if (exist) {
        exist.message = message
      } else {
        this.list.unshift(conversation)
      }
    },
    /**
     * 更新消息
     * @param {*} id 消息ID
     * @param {*} conversation 会话
     */
    updateMessage(messageId, conversation){
      for (let i = 0; i < this.list.length; i++) {
        const row = this.list[i];
        if (messageId === row.message.id){
          row.message = conversation.message
          return
        }
      }
    },
    /**
     * 设置未读
     * @param {*} id 
     */
    setUnread(id) {
      const conversation = this.list.find(item => item.id === id)
      if (conversation.unread) {
        conversation.unread += 1
      } else {
        conversation.unread = 1
      }
    },
    /**
     * 设置已读
     * @param {*} id 
     * @returns 
     */
    setRead(id) {
      const conversation = this.list.find(item => item.id === id)
      if (conversation) {
        conversation.unread = 0
        return conversation
      }
      return null
    },
    /**
     * 设置选中
     * @param {*} conversation 
     */
    setActive(conversation) {
      if (!conversation) {
        this.active = null
        return
      }

      // 如果是从会话列表点击的，需要设置已读
      const existingConversation = this.list.find(item => item.id === conversation.id)
      if (existingConversation) {
        // 更新现有会话的未读状态
        this.setRead(conversation.id)
        // 使用列表中的会话数据，确保群组信息完整
        if (existingConversation.group) {
          this.active = {
            ...existingConversation,
            type: 'group',
            group: {
              ...existingConversation.group,
              id: existingConversation.group.id,
              name: existingConversation.group.name,
              avatar: existingConversation.group.avatar,
              ownerId: existingConversation.group.ownerId,
              memberCount: existingConversation.group.memberCount,
              onlineCount: existingConversation.group.onlineCount
            }
          }
        } else {
          this.active = {
            ...existingConversation,
            type: 'friend'
          }
        }
      } else {
        // 如果是新会话（比如从群组列表点击进入），保持完整的会话数据
        this.active = {
          ...conversation,
          unread: 0,
          type: conversation.group ? 'group' : 'friend'
        }
      }
    },
    /**
     * 更新用户在线状态
     * @param {*} userId 用户ID
     * @param {*} online 在线状态
     */
    updateUserOnline(userId, online) {
      for (let i = 0; i < this.list.length; i++) {
        const { friend } = this.list[i];
        if (friend && friend.userId === userId) {
          friend.online = online
          break
        }
      }
    },
    /**
     * 清除数据
     */
    clear() {
      clearJson(this.$state)
    }
  }
})
